package v1

import (
	"fmt"
	"usplatformserver/global"
	"usplatformserver/internal/service"
	"usplatformserver/pkg/app"
	"usplatformserver/pkg/errcode"

	"github.com/gin-gonic/gin"
)

type AiRecommendReq struct{}

func NewAiRecommendReq() AiRecommendReq {
	return AiRecommendReq{}
}

// AI推荐获取结果
type recommendRet struct {
	RecommendRet []*int
	Err          error
}

// @Summer 获取Ai推荐结果
// @Produce json
// @param organType query int true "检查类型"
// @Param patientStamp query string false "患者时间戳"
// @Success 200 {object} model.AiRecommendTubercleSwaggerSuccess "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/ai/recommend [get]
func (t *AiRecommendReq) GetAiRecommendTubercles(c *gin.Context) {
	param := service.AiRecommendRequest{}
	response := app.NewResponse(c)

	valid, errs := app.BindAndValid(c, &param)
	if !valid {
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}

	getChan := make(chan recommendRet, 1)

	go func() {
		addr := fmt.Sprintf("tcp://%v:%d", global.ZMQSettings.Addr, global.ZMQSettings.Port)
		var ret recommendRet
		svc := service.New(c.Request.Context())
		recommendRet, err := svc.GetAiRecommendTubercles(addr, &param)
		ret.Err = err
		ret.RecommendRet = recommendRet
		getChan <- ret
	}()

	for {
		ret := <-getChan
		if ret.Err != nil {
			global.Logger.Infof("svc.GetAiRecommendTubercles failed: %v", ret.Err)
			response.ToErrorResponse(errcode.ErrorGetAiRecommendRetFail)
			break
		} else {
			response.ToResponseListWithoutPager(ret.RecommendRet)
			break
		}
	}
	close(getChan)
}
